package com.cy.lib.download;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by CY on 2015/8/21
 */
public class DownloadService extends Service implements Download.OnDownloadListener {

    public static final String ACTION_DOWNLOAD = "com.cy.lib.download.DownloadService.ACTION_DOWNLOAD";
    public static final String EXTRA_SHOW_NOTIFY = "com.cy.lib.download.DownloadService.EXTRA_SHOW_NOTIFY";

    private ExecutorService mThreadPool = Executors.newCachedThreadPool();
    private NotificationManager mNotificationManager;
    private Notification mNotify;
    private int currentProgress;

    public static void startActionDownload(Context context, String downloadUrl, File targetFile, boolean showNotify) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.setAction(ACTION_DOWNLOAD);
        intent.putExtra(Download.EXTRA_DOWNLOAD_URL, downloadUrl);
        intent.putExtra(Download.EXTRA_TARGET_FILE, targetFile);
        intent.putExtra(EXTRA_SHOW_NOTIFY, showNotify);
        context.startService(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }


    public class MyBinder extends Binder {

        public void startDownload(String downloadUrl, File targetFile, Download.OnDownloadListener listener) {
            Intent intent = new Intent();
            intent.putExtra(Download.EXTRA_DOWNLOAD_URL, downloadUrl);
            intent.putExtra(Download.EXTRA_TARGET_FILE, targetFile);
            try {
                handleDownload(intent, listener);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();
            switch (action) {
                case ACTION_DOWNLOAD:
                    try {
                        handleDownload(intent, this);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    public void handleDownload(Intent intent, Download.OnDownloadListener downloadListener) throws IOException {
        String mDownloadUrl = intent.getStringExtra(Download.EXTRA_DOWNLOAD_URL);
        File mTargetFile = (File) intent.getSerializableExtra(Download.EXTRA_TARGET_FILE);
        new Download(mDownloadUrl, mTargetFile, downloadListener).executeOnExecutor(mThreadPool);
    }

    @Override
    public void downloadState(Download.DownloadState state, Download.DownloadInfo info) {
        switch (state) {
            case START:
                currentProgress=0;
                break;
            case PROGRESS:
                int pro = (int) (info.getCurrentProgress() * 100 / info.getContentLength());
                if (currentProgress != pro) {
                    currentProgress = pro;
                    startNotify(info);
                }
                break;
            case COMPLETE:
                currentProgress=0;
                Intent intent = new Intent(Download.BROAST_DOWNLOAD_COMPLETE);
                intent.putExtra(Download.EXTRA_DOWNLOAD_URL, info.getDownloadUrl());
                intent.putExtra(Download.EXTRA_TARGET_FILE, info.getTargetFile());
                sendBroadcast(intent);
                break;
            case ERROR:
                break;

        }
    }


    private void startNotify(Download.DownloadInfo info) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        builder.setSmallIcon(android.R.drawable.btn_dropdown);
        String text = null;
        int flags;
        if (info.getCurrentProgress() < info.getContentLength()) {
            flags = Notification.FLAG_ONGOING_EVENT;
            text = "正在下载...";
        } else {
            flags = Notification.FLAG_AUTO_CANCEL;
            text = "下载完成";
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(info.getTargetFile()), "application/vnd.android.package-archive");
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
        }


        builder.setContentTitle(text).setProgress((int) info.getContentLength(), (int) info.getCurrentProgress(), false);
        mNotify = builder.build();
        mNotify.flags = flags;
        mNotificationManager.notify(1000, mNotify);
    }

}
